package com.cpa.admin.controller;

import com.cpa.admin.config.WebSecurityConfig;
import com.cpa.admin.model.UserDo;
import com.cpa.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author zhen.zhao01
 * @CreateDate 2018/10/31
 */
@Controller
@RequestMapping
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping("login")
    public String loginPage(@RequestParam(required = false)String productName, HttpServletRequest request) {
        if (!StringUtils.isEmpty(productName)) {
            request.setAttribute("productName", "产品: " + productName + " 登录");
        }else{
            request.setAttribute("productName", "登录");
        }
        return "login";
    }

    @PostMapping("login")
    public String login(UserDo userDo, HttpServletRequest request, HttpSession session, HttpServletResponse response){
        boolean verify = userService.verify(userDo.getUsername(), userDo.getPassword());
        if (!verify) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            throw new RuntimeException("password_error");
        }
        session.setAttribute(WebSecurityConfig.SESSION_KEY,userDo.getUsername());

        if (userService.isAdmin(userDo.getUsername())) {
            return "redirect:/";
        }else {
            return "redirect:/user_page";
        }
    }


    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(WebSecurityConfig.SESSION_KEY);
        return "redirect:/login";
    }

}
